package com.dl698.axdr;

import com.dl698.asn1.axdr.AxdrType;
import com.dl698.util.ReverseByteArrayInputStream;
import com.dl698.util.ReverseByteArrayOutputStream;

/**
 * AxdrVisibleString类
 * 实现可见字符串数据的编解码
 * 
 * @author wind
 * @version 1.1.1
 */
public class AxdrVisibleString implements AxdrType {
    private String value = "";

    public AxdrVisibleString() {
    }

    public AxdrVisibleString(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) {
        int codeLength = 0;

        // 解码字符串长度
        Unsigned8 lengthField = new Unsigned8();
        lengthField.setConst();
        codeLength += lengthField.decode(input);
        int length = (int) lengthField.getValue();

        // 解码字符串内容
        byte[] bytes = new byte[length];
        for (int i = 0; i < length; i++) {
            bytes[i] = (byte) input.read();
        }
        this.value = new String(bytes);

        return codeLength + length;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) {
        int codeLength = 0;

        // 编码字符串长度
        Unsigned8 lengthField = new Unsigned8();
        lengthField.setConst();
        byte[] bytes = this.value.getBytes();
        lengthField.setMinMaxVal(0, 255, bytes.length);
        codeLength += lengthField.encode(output);

        // 编码字符串内容
        try {
            output.writeByte(bytes);
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        }

        return codeLength + bytes.length;
    }

    @Override
    public String toString() {
        return "\"" + this.value + "\"";
    }
}